package com.maplexl.shiroJwtRedis.bean;

import com.maplexl.shiroJwtRedis.mapper.UserMapper;
import com.maplexl.shiroJwtRedis.pojo.User;
import com.maplexl.shiroJwtRedis.pojo.vo.JwtToken;
import com.maplexl.shiroJwtRedis.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 枫叶
 * @date 2020/11/1
 */
@Component
@Slf4j
public class MyReailm extends AuthorizingRealm {
    @Resource
    UserMapper userMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 用户授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("用户授权");
        long userId = JwtUtil.getUserId(principalCollection.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = userMapper.selectById(userId);
        Integer authority = user.getAuthority();
        Set<String> role = new HashSet<>();
        /*
         * 权限说明：2查看权限，3查看和编辑权限，
         * 6查看和授权权限，7查看、编辑、授权权限
         */
        switch (authority) {
            case 2:
                role.add("view");
                break;
            case 3:
                role.add("view");
                role.add("edit");
                break;
            case 6:
                role.add("view");
                role.add("authorization");
                break;
            case 7:
                role.add("view");
                role.add("edit");
                role.add("authorization");
                break;
            default:
                role.add("tourist");
        }
        //设置角色集合
        info.setRoles(role);
        return info;
    }

    /**
     * 用户身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("身份认证");
        String token = (String) authenticationToken.getCredentials();
        long userId = JwtUtil.getUserId(token);
        log.info(userId+"");
        User user = userMapper.selectById(userId);
        if (userId <= 0 || user == null) {
            throw new AuthenticationException("认证失败！");
        }
        return new SimpleAuthenticationInfo(token, token, "MyRealm");
    }
}
